package data

import (
	"commerce/common"
	"commerce/model"
	"database/sql"
	"fmt"
	"strconv"
)

func PageBrand(pageNo, pageSize int, name string) (*common.Page, error) {

	whereSql := composeSearchQuerySql(name)

	row := common.DB.QueryRow("select count(*) FROM brand" + whereSql)
	var totalRecords int
	if err := row.Scan(&totalRecords); err != nil {
		return nil, err
	}
	stmt, err := common.DB.Prepare("select id, `name`, logo, description, show_status, first_letter, sort FROM brand" + whereSql + " LIMIT ?, ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query((pageNo-1)*pageSize, pageSize)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var bs []model.Brand
	for rows.Next() {
		b := model.Brand{}
		if err := rows.Scan(&b.Id, &b.Name, &b.Logo, &b.Description, &b.ShowStatus, &b.FirstLetter, &b.Sort); err != nil {
			return nil, fmt.Errorf("品牌分页数据有误:%s", err.Error())
		}
		bs = append(bs, b)
	}
	return common.NewPage(bs, pageNo, pageSize, totalRecords), nil
}

func ListAllBrand(showStatus int) ([]model.Brand, error) {

	stmt, err := common.DB.Prepare("select id, `name` FROM brand where show_status = ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(showStatus)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var bs []model.Brand
	for rows.Next() {
		b := model.Brand{}
		if err := rows.Scan(&b.Id, &b.Name); err != nil {
			return nil, fmt.Errorf("品牌所有有效数据有误:%s", err.Error())
		}
		bs = append(bs, b)
	}
	return bs, nil
}

func GetBrandById(id int) (*model.Brand, error) {

	sqlTpl := "select b.id, b.`name`, b.logo, b.description, b.show_status, b.first_letter, b.sort, r.catelog_id, r.catelog_name FROM brand b inner join category_brand_relation r on b.id = r.brand_id where b.id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(id)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var b model.Brand
	var cs []model.Category
	for rows.Next() {
		if err := rows.Scan(&b.Id, &b.Name, &b.Logo, &b.Description, &b.ShowStatus, &b.FirstLetter, &b.Sort, &b.CategoryId, &b.CategoryName); err != nil {
			return nil, fmt.Errorf("品牌id查询数据有误:%s", err.Error())
		}
		c := model.Category{Id: b.CategoryId, Name: b.CategoryName}
		cs = append(cs, c)
	}
	b.OwnCategories = cs

	return &b, nil
}

func AddBrand(tx *sql.Tx, b model.Brand) (int, error) {

	sqlTpl := `insert into brand(name, logo, description, show_status, first_letter, sort) VALUES (?, ?, ?, ?, ?, ?)`

	stmt, err := tx.Prepare(sqlTpl)
	if err != nil {
		return 0, err
	}
	defer stmt.Close()
	result, err := stmt.Exec(b.Name, b.Logo, b.Description, b.ShowStatus, b.FirstLetter, b.Sort)

	if err != nil {
		return 0, fmt.Errorf("save brand err: %v", err)
	}
	id, err := result.LastInsertId()

	if err != nil {
		return 0, fmt.Errorf("save brand insert id err: %v", err)
	}
	return int(id), nil
}

func UpdateBrand(tx *sql.Tx, b model.Brand) (int, error) {

	var sqlTpl string
	if len(b.Logo) > 0 {
		sqlTpl = "update brand set `name`=?, logo=?, description=?, first_letter = ?, sort = ? WHERE id = ?"
	} else {
		sqlTpl = "update brand set `name`=?, description=?, first_letter = ?, sort = ? WHERE id = ?"
	}

	stmt, err := tx.Prepare(sqlTpl)
	if err != nil {
		return 0, err
	}
	defer stmt.Close()

	var result sql.Result
	if len(b.Logo) > 0 {
		result, err = stmt.Exec(b.Name, b.Logo, b.Description, b.FirstLetter, b.Sort, b.Id)
	} else {
		result, err = stmt.Exec(b.Name, b.Description, b.FirstLetter, b.Sort, b.Id)
	}
	if err != nil {
		return 0, fmt.Errorf("update brand err:%v", err.Error())
	}
	rowsAffected, err := result.RowsAffected()
	return int(rowsAffected), err
}

//func UpdateCategoryBrand(tx *sql.Tx, brandId int, categoryId int, categoryName string) (int, error) {
//
//	stmt, err := tx.Prepare("update category_brand_relation set catelog_id = ?, catelog_name = ? WHERE brand_id = ?")
//	if err != nil {
//		return 0, err
//	}
//	defer stmt.Close()
//
//	var result sql.Result
//	result, err = stmt.Exec(categoryId, categoryName, brandId)
//	if err != nil {
//		return 0, fmt.Errorf("update category brand rel err:%v", err.Error())
//	}
//	rowsAffected, err := result.RowsAffected()
//	return int(rowsAffected), err
//}

func UpdateBrandStatus(id, status int) error {

	sqlTpl := "update brand set show_status = ? WHERE id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(status, id)

	return err
}

func UpdateCategoryName(categoryId int, categoryName string) error {

	stmt, err := common.DB.Prepare("update category_brand_relation set catelog_name = ? WHERE catelog_id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(categoryName, categoryId)

	return err
}

func DeleteCategoryBrand(tx *sql.Tx, brandId int) error {

	stmt, err := tx.Prepare("delete from category_brand_relation where brand_id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(brandId)

	return err
}

func AddCategoryBrand(tx *sql.Tx, brandId int, brandName string, cs []string) error {

	stmt, err := tx.Prepare("insert into category_brand_relation (brand_id, catelog_id, brand_name, catelog_name) VALUES (?,?,?,?)")
	if err != nil {
		return err
	}
	defer stmt.Close()

    var id int
	var category *model.Category
	for _, cid := range cs {
		id, err = strconv.Atoi(cid)
		if err != nil {
			return err
		}
		category, err = GetCategoryById(id)
		if err != nil {
			return err
		}
		_, err = stmt.Exec(brandId, id, brandName, category.Name)
        if err != nil {
			return err
		}
	}
	return err
}

// ----------------app 专用接口开始-----------------------

func ListAppBrand() ([]model.Brand, error) {

	stmt, err := common.DB.Prepare("select distinct b.id, b.`name`, b.Logo, b.description, b.sort FROM brand b inner join goods g on b.id = g.brand_id where b.show_status = 1 and g.status = 1 order by b.sort desc")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query()
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var bs []model.Brand
	for rows.Next() {
		b := model.Brand{}
		if err := rows.Scan(&b.Id, &b.Name, &b.Logo, &b.Description, &b.Sort); err != nil {
			return nil, fmt.Errorf("品牌app有效数据有误:%s", err.Error())
		}
		bs = append(bs, b)
	}
	return bs, nil
}

func ListGoodsIdByBrandId(brandId, status int) ([]int, error) {

	stmt, err := common.DB.Prepare("SELECT id FROM goods where brand_id = ? AND `status` = ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(brandId, status)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var gs []int
	for rows.Next() {
		var goodsId int
		if err := rows.Scan(&goodsId); err != nil {
			return nil, fmt.Errorf("根据品牌查询上架商品数据有误:%s", err.Error())
		}
		gs = append(gs, goodsId)
	}
	return gs, nil
}
